package com.taldh.algorithm.bit;

public class HammingWeight {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        // & 1运算
        int count = 0;
        for( int i=0; i<32; i++){
            if( (n & 1) == 1 ) count++;
            n >>= 1;
        }
        return count;
    }

    public int hammingWeight2(int n) {
        int cnt = 0;
        while (n != 0) {
            n &= n - 1;
            ++cnt;
        }
        return cnt;
    }
}